package com.suntront.module_datasynch.taskup

import androidx.lifecycle.rxLifeScope
import com.mtjsoft.www.kotlinmvputils.base.BaseRecycleViewModel
import com.mtjsoft.www.kotlinmvputils.imp.AndCallBackListImp
import com.mtjsoft.www.kotlinmvputils.model.LoadState
import com.mtjsoft.www.kotlinmvputils.rxhttp.RxUrl
import com.mtjsoft.www.kotlinmvputils.rxhttp.entity.Response
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.code
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.msg
import com.suntront.lib_db.AppDatabase
import com.suntront.lib_db.table.MeterT
import com.suntront.lib_db.table.UserT
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.async
import rxhttp.await
import rxhttp.wrapper.param.RxHttp

/**
 * @author mtj
 * @Package com.suntront.module_datasynch.taskup
 * @date 2020-05-27 10:16:07
 */

class TaskUpViewModel : BaseRecycleViewModel<MeterT>() {

    val adminId = MMKV.defaultMMKV().getString("AdminID", "")
    val adminName = MMKV.defaultMMKV().getString("AdminName", "")

    /**
     * 获取列表数据
     */
    override fun getListDataInThread(pager: Int, callBackListImp: AndCallBackListImp<MeterT>) {
        rxLifeScope.launch({
            // 异步获取
            val list: MutableList<MeterT> = async {
                AppDatabase.getDb().meterDao().queryMeterTsByAdminIdNoUp(adminId)
            }.await()
            callBackListImp.onSuccess(list)
        }, {
            //异常回调，这里的it为Throwable类型
            val code = it.code
            val msg = it.msg
            showToastUI(msg)
            loadState.postValue(LoadState.NODATA)
        })
    }

    /**
     * 上传数据
     */
    fun update() {
        val choosePosition = HashMap<Int, Int>()
        for (i in list.value!!.indices) {
            if (list.value!![i].isChoose) {
                choosePosition[i] = list.value!![i].rosterId
            }
        }
        if (choosePosition.isEmpty()) {
            showToastUI("请选择要上传的表册")
            return
        }
        rxLifeScope.launch {
            // 异步获取多个册本下的 待上传任务
            val listUserT: MutableList<UserT> = async {
                AppDatabase.getDb().userDao()
                    .queryUpLoadByRosterId(choosePosition.values.toIntArray())
            }.await()
            if (listUserT.isEmpty()) {
                showToastUI("没有要上传的数据")
                return@launch
            }
            // 拼接上传字符串
            val jsondata = StringBuilder()
            jsondata.append("{\"UserInfos\":")
            jsondata.append("[")
            for (i in listUserT.indices) {
                jsondata.append(listUserT[i].toSiginString())
                if (i < listUserT.lastIndex) {
                    jsondata.append(",")
                }
                // 预先设置为已上传
                listUserT[i].upLoad = false
            }
            jsondata.append("]")
            jsondata.append("}")
            rxLifeScope.launch({    //通过launch方法开启一个协程
                val data = RxHttp.postJson(RxUrl.UPDATE_USER)
                    .addAll(jsondata.toString())
                    .await<Response<List<String>>>()
                if (data.isResult) {
                    val i = async {
                        AppDatabase.getDb().userDao().updateUsers(listUserT)
                        val meters : MutableList<MeterT> = ArrayList()
                        for (key in choosePosition.keys) {
                            val model = list.value!![key]
                            model.unUpLoadCount = 0
                            meters.add(model)
                        }
                        AppDatabase.getDb().meterDao().updateMetes(meters)
                    }.await()
                    showToastUI(data.msg)
                    // 刷新
                    onRefresh()
                } else {
                    showToastUI("上传失败")
                }
            }, {
                //异常回调，这里的it为Throwable类型
                val code = it.code
                val msg = it.msg
                showToastUI(msg)
            }, {
                showLoadingUI("正在上传...", false)
            }, {
                hideLoadingUI()
            })
        }
    }
}